package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    EmployeeMapper mapper;

    @Override
    public int insert(Employee record) {
        String password = record.getPassword();
        //加密(把用户名当做盐,加密两次)
        Md5Hash hash = new Md5Hash(password,record.getUsername(),2);
        //设置加密后的密码
        record.setPassword(hash.toString());

        int count = mapper.insert(record);

        List<Role> roles = record.getRoles();
        //关联关系
        for (Role role : roles) {
            mapper.insertRoleRelation(record.getId(),role.getId());
        }
        return count;
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Employee record) {

        //删除关系
        mapper.deleteRoleRelation(record.getId());

        List<Role> roles = record.getRoles();
        //关联关系
        for (Role role : roles) {
            mapper.insertRoleRelation(record.getId(),role.getId());
        }

        return mapper.updateByPrimaryKey(record);
    }

    @Override
    public PageResult query(QueryObject qo) {
        //查询总数
        int count = mapper.queryCount();
        //如果总数>1就查询结果集
        if(count>0){
           return new PageResult(count,mapper.queryList(qo));
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }

    @Override
    public Boolean validateName(String username,Long id) {
        Employee employee = mapper.selectByUsername(username);
        //如果employee找不到,用户名不重复,验证通过,返回true
        //如果前台传过来的id和数据库查询到的id相同,意为相同的用户,在做编辑操作,验证也通过,返回true
        return employee==null||employee.getId()==id;
    }

    @Override
    public void changeState(Long id) {
        mapper.changeState(id);
    }

    @Override
    public Employee selectByUsername(String username) {
        return mapper.selectByUsername(username);
    }
}
